package com.ujs.leetcode.ThreeSum;

import java.util.*;

/**
 * @author zhangshihao
 * @create 2023-10-17 19:15
 */
public class ThreeSum {
    public static void main(String[] args) {
        int[] nums = new int[]{-1, 0, 1, 2, -1, -4};
        System.out.println(threeSum2(nums));
    }


    /**
     * 双指针写法
     *
     * @param nums
     * @return
     */
    public static List<List<Integer>> threeSum2(int[] nums) {
        // 数组排序
        sortInt(nums, 0, nums.length - 1);
        System.out.println(Arrays.toString(nums));
        List<List<Integer>> result = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > 0) {
                return result;
            }
            if (i > 0 && nums[i] == nums[i-1]) { // 去重a
                continue;
            }

            int left = i + 1;
            int right = nums.length - 1;
            while (left < right) {
                int sum = nums[i] + nums[left] + nums[right];
                if (sum > 0) {
                    right--;
                } else if (sum < 0) {
                    left++;
                } else {
                    result.add(Arrays.asList(nums[i], nums[left], nums[right]));
                    // 去重逻辑 应该放在找到一个三元组之后，对b和c去重
                    while (right > left && nums[right] == nums[right - 1]) right--;
                    while (right > left && nums[left] == nums[left + 1]) left++;
                    right--;
                    left++;
                }
            }
        }
        return result;
    }


    /**
     * 快速排序
     *
     * @param nums
     * @return
     */
    public static void sortInt(int[] nums, int begin, int end) {
        if (begin > end) {
            return;
        }
        int k = nums[begin], i = begin, j = end;
        while (i != j) {
            while (nums[j] >= k && j > i) {
                j--;
            }
            while (nums[i] <= k && j > i) {
                i++;
            }
            if (j > i) {
                int temp = nums[i];
                nums[i] = nums[j];
                nums[j] = temp;
            }
        }
        nums[begin] = nums[i];
        nums[i] = k;
        sortInt(nums, begin, i - 1);
        sortInt(nums, i + 1, end);
    }
}
